<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAddPrimary"
            v-hasPermi="['shangpin:classify:add']"
        >添加一级分类</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="classifyTreeList"
        @selection-change="handleSelectionChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类名称" align="left" prop="categoryName">
        <template #default="scope">
          <span v-if="scope.row.level === 1" style="font-weight: bold;">
            {{ scope.row.categoryName }}
          </span>
          <span v-else>
            {{ scope.row.categoryName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 'enabled'" type="success">正常启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="佣金" align="left" prop="commissionRate">
        <template #default="scope">
          {{ Number(scope.row.commissionRate).toFixed(2) }}%
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-dropdown>
            <el-button
                size="small"
                style="border: 1px solid #dcdfe6; background-color: #fff; color: #606266; border-radius: 4px; padding-left: 6px"
            >
              操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleUpdate(scope.row)" v-hasPermi="['shangpin:classify:edit']">
                  <el-icon><Edit /></el-icon>编辑
                </el-dropdown-item>
                <el-dropdown-item @click="handleToggleStatus(scope.row)" v-hasPermi="['shangpin:classify:edit']">
                  <el-icon><Warning /></el-icon>{{ scope.row.status === 'enabled' ? '禁用' : '启用' }}
                </el-dropdown-item>
                <el-dropdown-item @click="handleDelete(scope.row)" v-hasPermi="['shangpin:classify:remove']">
                  <el-icon><Delete /></el-icon>删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
              v-if="scope.row.level < 3"
              type="danger"
              size="small"
              @click="handleAddSub(scope.row)"
              v-hasPermi="['shangpin:classify:add']"
              style="margin-left: 8px; border-radius: 4px; padding-right: 7px"
          >
            <el-icon><Plus /></el-icon>添加子分类
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="classifyRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId" v-if="form.level > 1">
          <el-select v-model="form.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="层级" prop="level">
          <el-input-number v-model="form.level" :min="1" :max="3" placeholder="请输入层级" />
        </el-form-item>
        <el-form-item label="佣金比例(%)" prop="commissionRate">
          <el-input-number
              v-model="form.commissionRate"
              :min="0"
              :max="100"
              :precision="2"
              placeholder="请输入佣金比例"
          />
        </el-form-item>
        <el-form-item label="分类图标URL" prop="categoryIcon">
          <el-input v-model="form.categoryIcon" placeholder="请输入分类图标URL" />
        </el-form-item>
        <el-form-item label="排序值" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" placeholder="请输入排序值（数字越小越靠前）" />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch
              v-model="form.status"
              active-value="enabled"
              inactive-value="disabled"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Classify">
import { listClassify, getClassify, delClassify, addClassify, updateClassify } from "@/api/shangpin/classify"
import { Plus, Edit, Delete, ArrowDown, Warning } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()

const classifyList = ref([])
const classifyTreeList = ref([])
const parentOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000, // 增大页面大小以获取所有分类
    categoryName: null,
  },
  rules: {
    categoryName: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "层级不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 构建树形结构
function buildTree(list) {
  const map = {}
  const result = []

  // 创建映射
  list.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  // 构建树形结构
  list.forEach(item => {
    if (item.parentId) {
      // 有父节点
      if (map[item.parentId]) {
        map[item.parentId].children.push(map[item.id])
      }
    } else {
      // 根节点
      result.push(map[item.id])
    }
  })

  return result
}

/** 查询商品分类列表 */
function getList() {
  loading.value = true
  listClassify(queryParams.value).then(response => {
    classifyList.value = response.rows
    classifyTreeList.value = buildTree(response.rows)
    total.value = response.total
    loading.value = false

    // 更新父分类选项
    updateParentOptions()
  })
}

// 更新父分类选项
function updateParentOptions() {
  parentOptions.value = classifyList.value.filter(item => item.level < 3)
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    creator: null,
    createTime: null,
    isDeleted: null,
    updater: null,
    updateTime: null,
    commissionRate: 5.00,
    categoryIcon: null,
    level: 1,
    categoryName: null,
    parentId: null,
    sortOrder: 0,
    status: 'enabled'
  }
  proxy.resetForm("classifyRef")
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增一级分类按钮操作 */
function handleAddPrimary() {
  reset()
  form.value.level = 1
  form.value.parentId = null
  open.value = true
  title.value = "添加一级分类"
}

/** 添加子分类按钮操作 */
function handleAddSub(row) {
  reset()
  form.value.level = row.level + 1
  form.value.parentId = row.id
  open.value = true
  title.value = `添加${row.level === 1 ? '二级' : '三级'}分类`
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getClassify(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商品分类"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["classifyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateClassify(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addClassify(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除商品分类编号为"' + _ids + '"的数据项？').then(function() {
    return delClassify(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 切换状态按钮操作 */
function handleToggleStatus(row) {
  const statusText = row.status === 'enabled' ? '禁用' : '启用'
  const newStatus = row.status === 'enabled' ? 'disabled' : 'enabled'

  proxy.$modal.confirm(`是否确认${statusText}商品分类"${row.categoryName}"？`).then(function() {
    const updateData = {
      id: row.id,
      status: newStatus,
      categoryName: row.categoryName,
      level: row.level,
      parentId: row.parentId,
      commissionRate: row.commissionRate,
      categoryIcon: row.categoryIcon,
      sortOrder: row.sortOrder,
      isChannelSupported: row.isChannelSupported
    }
    return updateClassify(updateData)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess(`${statusText}成功`)
  }).catch(() => {})
}

getList()
</script>

<style scoped>
.el-table .el-table__row .el-icon {
  margin-right: 5px;
}
</style>
